#include <bits/stdc++.h>
using namespace std;

class Solution
{
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    int m, n;
    vector<vector<bool>> visit;
    vector<string> b;
    string w;
public:
    bool dfs(int i, int j, int pos)
    {
        if(pos == w.size() - 1) return true;
        visit[i][j] = true;
        for(int k = 0; k < 4; k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && b[x][y] == w[pos + 1]) {
                if(dfs(x, y, pos + 1)) return true;
            } 
        }
        visit[i][j] = false;
        return false;
    }
    bool exist(vector<string> &board, string word)
    {
        b = board;
        w = word;
        m = board.size();
        n = board[0].size();
        visit = vector<vector<bool>>(m, vector<bool>(n, false));
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(b[i][j] == w[0]) {
                    if(dfs(i, j, 0)) return true;
                }
            }
        }
        return false;
    }
};